package com.cb.common.webapp.listener;

import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.ContextLoaderListener;
import org.springmodules.validation.commons.DefaultBeanValidator;

import com.cb.common.menu.Menu;
import com.cb.common.util.ConfigUtil;
import com.cb.common.util.MenuUtil;
import com.cb.common.util.MsgUrlConfigUtil;
import com.cb.core.Constants;
import com.cb.core.util.AppUtil;
import com.cb.core.util.RequestUtil;
import com.cb.core.webapp.ServletContextHolder;
import com.cb.domain.service.system.AppResourceManager;

/**
 * 
 * @author sdm
 *
 */
public class StartupListener extends ContextLoaderListener implements ServletContextListener {
    private static final Log logger = LogFactory.getLog(StartupListener.class);

    @SuppressWarnings({"unchecked"})
    public void contextInitialized(ServletContextEvent event) {
    	super.contextInitialized(event);
    	
    	ServletContextHolder.getInstance().setServletContext(event.getServletContext());
    	MsgUrlConfigUtil.getInstance().init(event.getServletContext());  

		String filePath=event.getServletContext().getRealPath("/")+"WEB-INF/classes/conf/menu-config.xml";
		AppResourceManager  appResourceManager= (AppResourceManager) AppUtil.getById("appResourceManagerImpl");
		
		Map<String,Menu> menuMap=MenuUtil.constructMenus(filePath);
		event.getServletContext().setAttribute(Constants.APP_MENU, menuMap);
		
		//是否同步menu-config.xml中的菜单配置
		if(ConfigUtil.getInstance().getIsSynchMenu()){
			appResourceManager.doSynchMenu(menuMap.values());
		}
		
		// 设置contextPath
		RequestUtil.setContextPath(event.getServletContext().getContextPath());
    }

    /**
     * Shutdown servlet context (currently a no-op method).
     *
     * @param servletContextEvent The servlet context event
     */
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //LogFactory.release(Thread.currentThread().getContextClassLoader());
        //Commented out the above call to avoid warning when SLF4J in classpath.
        //WARN: The method class org.apache.commons.logging.impl.SLF4JLogFactory#release() was invoked.
        //WARN: Please see http://www.slf4j.org/codes.html for an explanation.
    }
}
